package com.kc.business.service.impl;

import com.kc.business.domain.BizRole;
import com.kc.business.domain.BizUser;
import com.kc.business.domain.BizUserRole;
import com.kc.business.domain.KcShareDistributionApply;
import com.kc.business.domain.vo.KcShareDistributionApplyVo;
import com.kc.business.enums.ShareDistributionApplyAuditStatusEnum;
import com.kc.business.mapper.BizUserMapper;
import com.kc.business.mapper.BizUserRoleMapper;
import com.kc.business.mapper.KcShareDistributionApplyMapper;
import com.kc.business.service.IBizRoleService;
import com.kc.business.service.KcShareDistributionApplyService;
import com.kc.common.constant.Constants;
import com.kc.common.constant.UserConstants;
import com.kc.common.core.domain.AjaxResult;
import com.kc.common.utils.SharePosterUtils;
import com.kc.common.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

/**
 * FileName: KcShareDistributionApplyServiceImpl
 * Author:   TP
 * Date:     2020-11-14 09:38
 * Description: 分销申请实现
 */
@Slf4j
@Service
public class KcShareDistributionApplyServiceImpl implements KcShareDistributionApplyService {

    @Autowired
    private KcShareDistributionApplyMapper distributionApplyMapper;

    @Autowired
    private BizUserMapper userMapper;

    @Autowired
    private IBizRoleService bizRoleService;

    @Autowired
    private BizUserRoleMapper userRoleMapper;
    @Resource
    private SharePosterUtils sharePosterUtils;

    @Override
    public List<KcShareDistributionApplyVo> getList(KcShareDistributionApplyVo apply) {
        return distributionApplyMapper.getList(apply);
    }

    @Override
    public KcShareDistributionApplyVo getInfoById(Integer id) {
        return distributionApplyMapper.getInfoById(id);
    }

    @Override
    @Transactional
    public AjaxResult audit(KcShareDistributionApply apply) {
        if (apply != null && apply.getId() > 0) {
            if (apply.getAuditStatus() != null && ShareDistributionApplyAuditStatusEnum.getAllStatus().contains(apply.getAuditStatus())) {
                // 如果为拒绝，拒绝原因必填
                if (ShareDistributionApplyAuditStatusEnum.AUDIT_REJECT.getValue().equals(apply.getAuditStatus())) {
                    if (StringUtils.isEmpty(apply.getRejectReason())) {
                        return AjaxResult.error("审核拒绝必须说明原因");
                    }
                }
                // 查询最新状态
                KcShareDistributionApply distributionApply = distributionApplyMapper.selectByPrimaryKey(apply.getId());
                if (!ShareDistributionApplyAuditStatusEnum.AUDITING.getValue().equals(distributionApply.getAuditStatus())) {
                    return AjaxResult.error(String.format("当前申请状态已为[%s]，不支持审核，请刷新",
                            ShareDistributionApplyAuditStatusEnum.getDesc(distributionApply.getAuditStatus())));
                }
                // 进行审核
                int result = distributionApplyMapper.updateByPrimaryKeySelective(apply);
                if (result > 0) {
                    // 如果为审核通过，需要更新用户信息
                    if (ShareDistributionApplyAuditStatusEnum.AUDIT_PASS.getValue().equals(apply.getAuditStatus())) {
                        // 设置用户为分销户
                        BizUser bizUser = userMapper.selectByPrimaryKey(distributionApply.getApplyUserId());
                        BizUser toUpdateUser = new BizUser();
                        toUpdateUser.setId(bizUser.getId());
                        toUpdateUser.setIsAgent(Integer.parseInt(Constants.YES));
                        if(bizUser.getAgentBindTime() == null) {
                            toUpdateUser.setAgentBindTime(LocalDateTime.now());
                        }else{
                            toUpdateUser.setAgentBindTime(bizUser.getAgentBindTime());
                        }
                        toUpdateUser.setAgentCode(String.format("FX%s", 100000 + apply.getId()));
                        //toUpdateUser.setPId(bizUser.getSourceId());
                        toUpdateUser.setSharePoster(sharePosterUtils.qrcode(bizUser.getId()));
                        userMapper.updateByPrimaryKeySelective(toUpdateUser);
                        // 给用户分配菜单权限
                        BizRole bizRole = bizRoleService.getByKey(UserConstants.ROLE_DISTRIBUTION_APP);
                        if (bizRole != null) {

                        } else {
                            throw new RuntimeException(
                                    String.format("操作失败：审核通过后为此用户分配分销角色失败，请联系管理员创建Key为%s的角色信息",
                                            UserConstants.ROLE_DISTRIBUTION_APP));
                        }
                    }
                    return AjaxResult.success();
                }
                return AjaxResult.error("数据库更新失败");
            } else {
                return AjaxResult.error("指定的审核状态错误");
            }
        }
        return AjaxResult.error("请指定要审核的记录");
    }

    @Override
    public void createSharePoster() {
        BizUser bizUser = new BizUser();
        //bizUser.setSharePoster("");
        bizUser.setIsAgent(1);
        List<BizUser> bizUserList = userMapper.select(bizUser);
        //System.out.println(bizUserList);
        for(BizUser bizUser1:bizUserList){
            String imagePath = sharePosterUtils.qrcode(bizUser1.getId());
            bizUser1.setSharePoster(imagePath);
            userMapper.updateByPrimaryKey(bizUser1);
        }
    }
}
